import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { liveStreamAPI } from '../services/api';
import { useAuth } from '../contexts/AuthContext';
import { LiveStream } from '../types';
import Avatar from '../components/Avatar';

const LiveStreamBroadcast: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { user } = useAuth();
  const [liveStream, setLiveStream] = useState<LiveStream | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [isLive, setIsLive] = useState(false);
  const [viewers, setViewers] = useState(0);
  const videoRef = useRef<HTMLVideoElement>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const peerConnectionsRef = useRef<Map<string, RTCPeerConnection>>(new Map());
  const socketRef = useRef<WebSocket | null>(null);

  const fetchLiveStream = useCallback(async () => {
    try {
      setLoading(true);
      const stream = await liveStreamAPI.getLiveStreamById(parseInt(id!));
      setLiveStream(stream);
      
      // 检查是否是主播
      if (stream.userId !== user?.id) {
        setError('您不是此直播的主播');
        return;
      }
    } catch (error: any) {
      setError(error.message || '获取直播信息失败');
    } finally {
      setLoading(false);
    }
  }, [id, user?.id]);

  useEffect(() => {
    if (id && user) {
      fetchLiveStream();
    }
  }, [id, user, fetchLiveStream]);

  const startLiveStream = async () => {
    if (!liveStream || !user) return;

    try {
      let stream: MediaStream;
      
      try {
        // 尝试获取真实的摄像头和麦克风
        stream = await navigator.mediaDevices.getUserMedia({
          video: true,
          audio: true
        });
      } catch (cameraError) {
        console.log('无法访问摄像头，使用模拟视频流');
        
        // 创建模拟视频流
        const canvas = document.createElement('canvas');
        canvas.width = 640;
        canvas.height = 480;
        const ctx = canvas.getContext('2d')!;
        
        // 创建模拟视频内容
        let frameCount = 0;
        const drawFrame = () => {
          // 清空画布
          ctx.fillStyle = '#1f2937';
          ctx.fillRect(0, 0, canvas.width, canvas.height);
          
          // 绘制模拟内容
          ctx.fillStyle = '#3b82f6';
          ctx.font = '48px Arial';
          ctx.textAlign = 'center';
          ctx.fillText('模拟直播', canvas.width / 2, canvas.height / 2 - 50);
          
          ctx.fillStyle = '#ffffff';
          ctx.font = '24px Arial';
          ctx.fillText(`直播时间: ${Math.floor(frameCount / 30)}秒`, canvas.width / 2, canvas.height / 2);
          
          ctx.fillStyle = '#10b981';
          ctx.font = '20px Arial';
          ctx.fillText(`观看人数: ${viewers}`, canvas.width / 2, canvas.height / 2 + 50);
          
          // 添加一些动画效果
          ctx.fillStyle = `hsl(${(frameCount * 2) % 360}, 70%, 60%)`;
          ctx.beginPath();
          ctx.arc(100 + (frameCount % 200), 100, 20, 0, 2 * Math.PI);
          ctx.fill();
          
          frameCount++;
          
          // 继续下一帧
          requestAnimationFrame(drawFrame);
        };
        
        drawFrame();
        
        // 将canvas转换为MediaStream
        stream = canvas.captureStream(30); // 30fps
        
        // 添加模拟音频轨道（静音）
        const audioContext = new AudioContext();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        gainNode.gain.value = 0; // 静音
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        oscillator.start();
        
        const audioTrack = audioContext.createMediaStreamDestination().stream.getAudioTracks()[0];
        if (audioTrack) {
          stream.addTrack(audioTrack);
        }
      }
      
      streamRef.current = stream;
      
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
      }

      // 开始直播
      const updatedStream = await liveStreamAPI.startLiveStream(liveStream.id, user.id);
      setLiveStream(updatedStream);
      setIsLive(true);

      // 初始化WebRTC信令
      initializeWebRTCSignaling(updatedStream.streamKey);

    } catch (error: any) {
      setError('启动直播失败: ' + error.message);
    }
  };

  const stopLiveStream = async () => {
    if (!liveStream || !user) return;

    try {
      // 停止媒体流
      if (streamRef.current) {
        streamRef.current.getTracks().forEach(track => track.stop());
        streamRef.current = null;
      }

      // 关闭WebSocket连接
      if (socketRef.current) {
        socketRef.current.close();
        socketRef.current = null;
      }

      // 关闭所有Peer连接
      peerConnectionsRef.current.forEach(connection => connection.close());
      peerConnectionsRef.current.clear();

      // 结束直播
      const updatedStream = await liveStreamAPI.endLiveStream(liveStream.id, user.id);
      setLiveStream(updatedStream);
      setIsLive(false);

    } catch (error: any) {
      setError('结束直播失败: ' + error.message);
    }
  };

  const initializeWebRTCSignaling = (streamKey: string) => {
    try {
      // 创建WebSocket连接
      const socket = new WebSocket('ws://localhost:8080/ws');
      socketRef.current = socket;
      
      socket.onopen = () => {
        console.log('WebSocket连接已建立');
        // 加入直播流
        socket.send(JSON.stringify({
          type: 'join',
          streamKey: streamKey,
          userId: user?.id.toString()
        }));
      };

      socket.onmessage = async (event) => {
        const message = JSON.parse(event.data);
        
        switch (message.type) {
          case 'join':
            handleViewerJoin(message);
            break;
          case 'leave':
            handleViewerLeave(message);
            break;
          case 'answer':
            handleAnswer(message);
            break;
          case 'ice-candidate':
            handleIceCandidate(message);
            break;
        }
      };

    } catch (error) {
      console.error('WebRTC信令初始化失败:', error);
    }
  };

  const handleViewerJoin = async (message: any) => {
    const viewerId = message.userId;
    
    try {
      // 创建RTCPeerConnection
      const configuration = {
        iceServers: [
          { urls: 'stun:stun.l.google.com:19302' }
        ]
      };
      
      const peerConnection = new RTCPeerConnection(configuration);
      peerConnectionsRef.current.set(viewerId, peerConnection);

      // 添加本地流
      if (streamRef.current) {
        streamRef.current.getTracks().forEach(track => {
          peerConnection.addTrack(track, streamRef.current!);
        });
      }

      // 创建offer
      const offer = await peerConnection.createOffer();
      await peerConnection.setLocalDescription(offer);

      // 发送offer
      if (socketRef.current) {
        socketRef.current.send(JSON.stringify({
          type: 'offer',
          offer: offer,
          targetUserId: viewerId
        }));
      }

      // 更新观看人数
      setViewers(prev => prev + 1);

    } catch (error) {
      console.error('处理观众加入失败:', error);
    }
  };

  const handleViewerLeave = (message: any) => {
    const viewerId = message.userId;
    
    // 关闭Peer连接
    const peerConnection = peerConnectionsRef.current.get(viewerId);
    if (peerConnection) {
      peerConnection.close();
      peerConnectionsRef.current.delete(viewerId);
    }

    // 更新观看人数
    setViewers(prev => Math.max(0, prev - 1));
  };

  const handleAnswer = async (message: any) => {
    const viewerId = message.userId;
    const peerConnection = peerConnectionsRef.current.get(viewerId);
    
    if (peerConnection) {
      try {
        await peerConnection.setRemoteDescription(new RTCSessionDescription(message.answer));
      } catch (error) {
        console.error('处理answer失败:', error);
      }
    }
  };

  const handleIceCandidate = async (message: any) => {
    const viewerId = message.userId;
    const peerConnection = peerConnectionsRef.current.get(viewerId);
    
    if (peerConnection) {
      try {
        await peerConnection.addIceCandidate(new RTCIceCandidate(message.candidate));
      } catch (error) {
        console.error('处理ICE候选失败:', error);
      }
    }
  };

  if (loading) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="text-center py-8">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  if (error || !liveStream) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
          {error || '直播不存在'}
        </div>
        <button 
          onClick={() => navigate('/live')}
          className="mt-4 btn btn-primary"
        >
          返回直播列表
        </button>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-4 md:py-8">
      <div className="bg-white rounded-lg shadow overflow-hidden">
        {/* 视频预览区域 */}
        <div className="aspect-video bg-gray-900 relative">
          <video 
            ref={videoRef}
            autoPlay
            muted
            playsInline
            className="w-full h-full"
          />
          
          {/* 直播状态指示器 */}
          <div className="absolute top-4 left-4">
            <span className={`px-2 py-1 rounded text-xs font-medium ${
              isLive 
                ? 'bg-red-500 text-white' 
                : 'bg-gray-500 text-white'
            }`}>
              {isLive ? 'LIVE' : 'OFFLINE'}
            </span>
          </div>
          
          {/* 观看人数 */}
          <div className="absolute top-4 right-4 bg-black bg-opacity-75 text-white text-xs px-2 py-1 rounded">
            {viewers} 观看
          </div>
        </div>
        
        {/* 直播信息 */}
        <div className="p-4 md:p-6">
          <h1 className="text-xl md:text-2xl font-bold text-gray-900 mb-2">{liveStream.title}</h1>
          <p className="text-gray-600 mb-4 text-sm md:text-base">{liveStream.description}</p>
          
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between space-y-4 sm:space-y-0">
            <div className="flex items-center space-x-3 md:space-x-4">
              <Avatar 
                user={user!} 
                size="md" 
              />
              <div>
                <p className="font-medium text-gray-900 text-sm md:text-base">{user?.username}</p>
                <p className="text-sm text-gray-500">主播</p>
              </div>
            </div>
            
            <div className="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-4 w-full sm:w-auto">
              {!isLive ? (
                <button
                  onClick={startLiveStream}
                  className="bg-red-600 text-white px-6 py-3 rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 text-sm md:text-base w-full sm:w-auto"
                >
                  开始直播
                </button>
              ) : (
                <button
                  onClick={stopLiveStream}
                  className="bg-gray-600 text-white px-6 py-3 rounded-md hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-gray-500 text-sm md:text-base w-full sm:w-auto"
                >
                  结束直播
                </button>
              )}
              
              <button
                onClick={() => navigate('/live')}
                className="px-4 py-3 border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm md:text-base w-full sm:w-auto"
              >
                返回列表
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default LiveStreamBroadcast; 